package cqrtplm.listener;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import cqrtplm.service.FlowControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;

import java.math.BigInteger;

@Slf4j
@CustomListener(category = "润通", description = "判断流程分支节点")
public class FlowBranchDetermineListener implements ExecutionListener {

    @CustomListenerField(description = "条件", defaultValue = "", required = true)
    private FixedValue condition;

    @Override
    public void notify(DelegateExecution execution) {
        long start = System.currentTimeMillis();
        String workFlowContainerId = execution.getProcessInstanceBusinessKey();
        log.info("----------润通----判断流程分支节点------开始------workFlowContainerId:{}----->>>",
                 workFlowContainerId);
        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = execution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }
        String finalWorkFlowContainerId = workFlowContainerId;
        FlowControlService flowControlService = SpringUtil.getBean(FlowControlService.class);
        String processInstanceId = execution.getProcessInstanceId();
        //        Map<String, Object> requestContext = RequestContext.currentContext();
        //        CompletableFuture.runAsync(() -> {
        //            RequestContext.attachContext(requestContext);

        try {
            int flag = 0;
            flowControlService.chooseFLowBranch(new BigInteger(finalWorkFlowContainerId), condition.getExpressionText(),
                                                execution);


        } catch (Exception e) {
            log.info("判断流程分支节点");
            log.error(ExceptionUtil.getMessage(e));
            log.error(ExceptionUtil.stacktraceToString(e, 100000));
        } finally {
//            RuntimeService runtimeService = SpringUtil.getBean(RuntimeService.class);
//            Execution singleResult = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).
//                    parentId(processInstanceId).singleResult();
//            runtimeService.setVariable(singleResult.getId(), "", flag);
//            runtimeService.messageEventReceived("", singleResult.getId());
        }
        //        });
        log.info("----------润通----判断流程分支节点,耗时：{}---->>>", System.currentTimeMillis() - start);
    }
}
